<?php
namespace app\admin\controller;

use app\BaseController;
use think\facade\view;
use app\Request;
use app\admin\model\AdminUser;

class Login extends BaseController
{

    //渲染页面
    public function index()
    {
        return view('login');
    }

    public function check( request $request ){

        //判断不是post请求失败
        if (!$this->request->isPost()) {
            return json([
                'status' => '1',
                'message' => '请求方式错误',
                'result' => '',
            ]);
        }

        //接收数据
        $data['username'] = $request->post('username','','trim');
        $data['password'] = $request->post('password','','trim');
        $data['captcha'] = $request->post('captcha','','trim');
        // $captcha = $request->post('captcha','','trim');

        //判断接值不能为空
        if (empty($data['username']) || empty($data['password']) || empty($data['captcha'])) {
            return json([
                'status' => '1',
                'message' => '参数不能为空',
                'result' => '',
            ]);
        }

        //登入验证码
        if(!captcha_check($data['captcha'])){
            // 验证失败
            return json([
                'status' => '1',
                'message' => '验证码不正确',
                'result' => '',
            ]);
           };

           //发送模型层
           $adminUserObj = new AdminUser();
           $adminUser = $adminUserObj->getAdminUserByUsername($data);

           //判断密码
            if ($adminUser['password'] != $data['password']) {
                return json([
                    'status' => '1',
                    'message' => '账号或密码错误',
                    'result' => '',
                ]);
            }

            //记录sesion
            session("admin.session_admin",$adminUser);
            
            //需要记录信息到mysql表中
            $updateData = [
                "last_login_time" => time(),
                "last_login_ip" => request()->ip(),
            ];
            
            $res = $adminUserObj->updataById($adminUser['id'],$updateData);

           if ($res) {
            return json([
                'status' => '0',
                'message' => '成功',
                'result' => '',
            ]);
           }else{
            return json([
                'status' => '0',
                'message' => '失败',
                'result' => '',
            ]);
           }
    }


}
